<!-- 视频监控flv格式 -->
<template>
  <div id="flv_video" :style="{ display: showScreen ? 'block' : 'none' }">
    <video
      :id="'myFlvVideo' + videoIndex"
      class="video-js"
      style="width: 100%; height: 100%; object-fit: fill"
      :muted="false"
      controls
      autoplay
    ></video>
  </div>
</template>
<script>
import {
  defineComponent,
  nextTick,
  onBeforeUnmount,
  onMounted,
  reactive,
  toRefs,
} from "vue";
import flvjs from "flv-h265";
import { LoadingOutlined } from "@ant-design/icons-vue";
import "video.js/dist/video-js.css";
export default defineComponent({
  props: {
    videoItem: {
      type: Object,
      default: () => {
        return {};
      },
    },
    videoIndex: {
      type: Number,
      default: 0,
    },
  },
  setup(props, context) {
    const state = reactive({
      showScreen: false,
      flvPlayer: null,
      videoSrc: props.videoItem.video,
    });

    onMounted(() => {
      nextTick(() => {
        createVideo();
        let timeout = setTimeout(() => {
          state.showScreen = true;
          clearTimeout(timeout);
        }, 200);
      });
    });

    const createVideo = () => {
      if (flvjs.isSupported()) {
        var videoElement = document.getElementById(
          "myFlvVideo" + props.videoIndex
        );
        state.flvPlayer = flvjs.createPlayer({
          type: "flv",
          isLive: true,
          hasAudio: false,
          url: state.videoSrc,
        });
        state.flvPlayer.attachMediaElement(videoElement);
        state.flvPlayer.load();
        state.flvPlayer.play();
        // 报错重连
        state.flvPlayer.on(flvjs.Events.ERROR, (errType, errDetail) => {
          if (state.flvPlayer) {
            destoryVideo();
            createVideo();
          }
        });
      }
    };

    const destoryVideo = () => {
      if (state.flvPlayer) {
        state.flvPlayer.pause();
        state.flvPlayer.unload();
        state.flvPlayer.detachMediaElement();
        state.flvPlayer.destroy();
        state.flvPlayer = null;
      }
    };

    onBeforeUnmount(() => {
      destoryVideo();
    });

    return {
      ...toRefs(state),
    };
  },
});
</script>

<style lang="less" scoped>
#flv_video {
  pointer-events: none;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  .videoPlayer {
    width: 100%;
    height: 100%;
  }
}
</style>
